package com.yun.baymax.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.yun.baymax.R;
import com.yun.baymax.bean.adapter.PasswordInfo;
import com.yun.baymax.utils.ToastUtils;
import com.yun.lib.utils.Encipher;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;


public class PasswordKeepAct extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    private ListView listView;
    private ItemListAdapter adapter;
    private EditText diaTitle;
    private EditText diaPsd;
    private EditText diaRemark;
    private EditText diaAccount;
    private AlertDialog.Builder builder;
    private AlertDialog alertDialog;
    private LayoutInflater inflater;
    private SwipeRefreshLayout refreshLayout;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.activity_password_keep;
    }

    @Override
    protected void initVariables() {
        inflater = getLayoutInflater();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createEditDialog(true, null);
            }
        });
        listView = (ListView) findViewById(R.id.list_view);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh);
        refreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.text_color_blue, R.color.voucher_color_red);
        refreshLayout.setOnRefreshListener(this);

        adapter = new ItemListAdapter(mContext);
        listView.setAdapter(adapter);
    }

    @Override
    protected void loadData() {
        refreshLayout.setRefreshing(true);
        BmobQuery<PasswordInfo> billQuery = new BmobQuery<>();
        billQuery.addWhereEqualTo("author", BmobUser.getCurrentUser().getUsername());
        billQuery.findObjects(new FindListener<PasswordInfo>() {
            @Override
            public void done(List<PasswordInfo> list, BmobException e) {
                refreshLayout.setRefreshing(false);
                if (e == null) {
                    adapter.setDatas(list);
                } else {
                    ToastUtils.showShortToast("暂无数据");
                }
            }
        });
    }

    private void createEditDialog(final boolean isAdd, final PasswordInfo passwordInfo) {
        View dialog = inflater.inflate(R.layout.dialog_add_password, null);
        diaTitle = (EditText) dialog.findViewById(R.id.et_bank);
        diaPsd = (EditText) dialog.findViewById(R.id.et_total);
        diaRemark = (EditText) dialog.findViewById(R.id.et_remark);
        diaAccount = (EditText) dialog.findViewById(R.id.et_account);

        builder = new AlertDialog.Builder(mContext);
        builder.setTitle(isAdd ? "添加帐号" : "修改帐号");
        builder.setView(dialog);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String title = diaTitle.getText().toString();
                String account = Encipher.encode(diaAccount.getText().toString());
                String psd = Encipher.encode(diaPsd.getText().toString());
                String sRemark = Encipher.encode(diaRemark.getText().toString());

                if (TextUtils.isEmpty(diaTitle.getText().toString())) {
                    return;
                }
                if (isAdd) {
                    PasswordInfo PasswordInfo = new PasswordInfo(title, account, psd, sRemark);
                    PasswordInfo.setAuthor(BmobUser.getCurrentUser().getUsername());
                    saveUP(PasswordInfo);
                    adapter.addDatas(PasswordInfo);
                } else {
                    passwordInfo.setTitle(title);
                    passwordInfo.setName(account);
                    passwordInfo.setPassword(psd);
                    passwordInfo.setRemark(sRemark);
                    updateUP(passwordInfo);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        alertDialog = builder.create();
        alertDialog.show();
    }

    //上传增加或修改的数据
    private void saveUP(PasswordInfo PasswordInfo) {
        PasswordInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e != null)
                    ToastUtils.showShortToast(e.getMessage());
                else
                    ToastUtils.showShortToast("添加成功");
            }
        });
    }

    //上传修改的数据
    private void updateUP(PasswordInfo PasswordInfo) {
        PasswordInfo.update(PasswordInfo.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                } else ToastUtils.showShortToast(e.getMessage());
            }
        });
    }

    //删
    private void deleteUP(PasswordInfo data) {
        data.delete(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null)
                    ToastUtils.showShortToast("删除成功");
                else ToastUtils.showShortToast(e.getMessage());
            }
        });
    }

    @Override
    public void onRefresh() {
        loadData();
    }

    public class ItemListAdapter extends BaseAdapter {

        private List<PasswordInfo> datas = new ArrayList<>();

        private Context context;
        private LayoutInflater layoutInflater;
        private View.OnClickListener onItemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewHolder holder = (ViewHolder) v.getTag();
                if (holder == null || holder.position >= datas.size())
                    return;
                onItemClick(v, datas.get(holder.position), holder, holder.position);
            }
        };

        public ItemListAdapter(Context context) {
            this.context = context;
            this.layoutInflater = LayoutInflater.from(context);
        }

        public void addDatas(PasswordInfo data) {
            datas.add(data);
            notifyDataSetChanged();
        }

        public void setDatas(List<PasswordInfo> datas) {
            this.datas = datas;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return datas == null ? 0 : datas.size();
        }

        @Override
        public PasswordInfo getItem(int position) {
            return datas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.item_password_list, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.position = position;
            initHolderViews(getItem(position), holder, position);
            convertView.setOnClickListener(onItemClickListener);
            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    deleteItem(getItem(position));
                    return false;
                }
            });
            return convertView;
        }

        private void initHolderViews(final PasswordInfo data, final ViewHolder holder, final int position) {
            holder.itemTitle.setText(data.getTitle());
            holder.account.setText(Encipher.decode(data.getName()));
        }

        private void deleteItem(final PasswordInfo data) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(data.getName());
            builder.setMessage("确认删除？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    datas.remove(data);
                    deleteUP(data);
                    adapter.notifyDataSetChanged();
                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }

        private void onItemClick(View convertView, final PasswordInfo data, ViewHolder holder, int position) {
            createEditDialog(false, data);
            diaTitle.setText(data.getTitle());
            diaPsd.setText(Encipher.decode(data.getPassword()));
            diaRemark.setText(Encipher.encode(data.getRemark()));
            diaAccount.setText(Encipher.decode(data.getName()));
        }

        protected class ViewHolder {
            private TextView itemTitle;
            private TextView account;
            private int position;

            public ViewHolder(View view) {
                itemTitle = (TextView) view.findViewById(R.id.item_title);
                account = (TextView) view.findViewById(R.id.item_account);
            }
        }
    }
}
